import React, { Component } from 'react'
import { Button } from 'antd'
import { Menu, Dropdown } from 'antd'
import { DownOutlined } from '@ant-design/icons'
import 'antd/dist/antd.less'

// 引入connect用于连接UI组件和redux
import {
    connect
} from 'react-redux'

import {
    increment,
    decrement,
    incrementAsync
} from '../../redux/count/action'

// 定义UI组件
class Count extends Component {

    state = {
        currentChooseNum: 0
    }

    componentDidMount() {
        // console.log(this.props)
    }

    // 菜单选中记录当前选中的值
    menuHandlerChoose = ({ key }) => {
        this.setState({
            currentChooseNum: +key
        })
    }

    // 点击+号
    increment = () => {
        const { currentChooseNum } = this.state
        this.props.increment(currentChooseNum)
    }

    // 点击-号
    decrement = () => {
        const { currentChooseNum } = this.state
        this.props.decrement(currentChooseNum)
    }

    // 奇数自增
    incrementIfOdd = () => {
        if (this.props.count % 2 === 1) {
            this.props.increment(1)
        }
    }

    // 异步自增
    incrementAsync = () => {
        this.props.incrementAsync(1, 500)
    }
    render() {
        const menu = (
            <Menu onClick={this.menuHandlerChoose}>
                <Menu.Item key={1}>1</Menu.Item>
                <Menu.Item key={2}>2</Menu.Item>
                <Menu.Item key={3}>3</Menu.Item>
            </Menu>
        )
        return (
            <div className="app">
                <h1>SUM: {this.props.count}</h1>
                <Dropdown overlay={menu}>
                    <a href="javascript;" className="ant-dropdown-link" onClick={e => e.preventDefault()}>
                        请选择... <DownOutlined />
                    </a>
                </Dropdown>
                &nbsp;&nbsp;<Button type="primary" shape="circle" onClick={this.increment}>+</Button>
                &nbsp;&nbsp;<Button shape="circle" onClick={this.decrement}>-</Button>
                &nbsp;&nbsp;<Button type="dashed" shape="round" onClick={this.incrementIfOdd}>为奇数则自增</Button>
                &nbsp;&nbsp;<Button type="dashed" shape="round" onClick={this.incrementAsync}>异步自增</Button>
                <h2>Person组件人口人数为：{this.props.personLen}</h2>

            </div>
        )
    }
}

// 将函数的返回值作为参数传给UI组件
// 必须是个对象，以键值对的形式
// 相同的属性，后传递的会覆盖掉先前传递的
const mapStateToProps = state => ({ count: state.count, personLen: state.person.length })

export default connect(mapStateToProps, {
    increment,
    decrement,
    incrementAsync
})(Count)

/* const mapDispatchToProps = _ => (
    // {
    //     increment: data => dispatch(createIncrementAction(data)),
    //     decrement: data => dispatch(createDecrementAction(data)),
    //     incrementAsync: (data, wait) => dispatch(createIncrementAsyncAction(data, wait))
    // }
    // 简洁版，利用react-redux自动分发
    {
        increment: createIncrementAction,
        decrement: createDecrementAction,
        incrementAsync: createIncrementAsyncAction
    }
) */
